package com.atguigu.srb.sms.feign;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.RandomRule;
import com.netflix.loadbalancer.Server;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;

//自定义ribbon的负载均衡策略： 随机
public class MyRandomRule extends RandomRule {

    @Override
    public Server choose(ILoadBalancer lb, Object key) {
        //获取 要远程访问的服务 在注册中心 成功注册在线的服务列表
        List<Server> servers = lb.getReachableServers();
        if(CollectionUtils.isEmpty(servers)){
            return null;
        }
        int index = RandomUtils.nextInt(0, servers.size());
        System.out.println(index);
        Server server = servers.get(index);
        return server;
    }
}
